const Controller = require('egg').Controller;

class GoodController extends Controller {
    // 验证 JWT token 的辅助方法
    async verifyToken() {
        const { ctx } = this;
        const token = ctx.request.header.token;

        if (!token) {
            throw new Error('请先登录');
        }

        try {
            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
            if (decode.type !== 'user') {
                throw new Error('无权限操作');
            }
            return decode;
        } catch (error) {
            if (error.name === 'TokenExpiredError') {
                throw new Error('登录已过期，请重新登录');
            } else if (error.name === 'JsonWebTokenError') {
                throw new Error('无效的token，请重新登录');
            } else {
                throw new Error('认证失败，请重新登录');
            }
        }
    }

    // 创建二手商品
    async create() {
        const { ctx, service } = this;

        try {
            // 更灵活的参数验证 - 允许images为字符串或数组
            const rules = {
                title: { type: 'string', required: true, max: 100 },
                description: { type: 'string', required: true },
                category: { type: 'string', required: true, max: 50 },
                price: { type: 'number', required: true, min: 0 },
                images: { type: 'string', required: true }, // 主要验证字符串
                contact_info: { type: 'string', required: true }
            };

            // 先验证基本规则
            ctx.validate(rules);

            const goodData = ctx.request.body;

            // 特殊处理images字段：如果是数组，转换为字符串
            if (goodData.images && Array.isArray(goodData.images)) {
                goodData.images = goodData.images.join(',');
            }

            // 从token中获取用户ID
            const decode = await this.verifyToken();

            // 设置卖家ID
            goodData.user_id = decode.user_id;

            const result = await service.good.create(goodData);

            ctx.body = {
                code: 0,
                data: result,
                msg: '创建成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '创建失败'
            };
        }
    }

    // 获取二手商品列表
    async list() {
        const { ctx, service } = this;

        try {
            const query = ctx.query;
            const result = await service.good.getGoods(query);

            ctx.body = {
                code: 0,
                data: result,
                msg: '获取成功'
            };
        } catch (error) {
            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取列表失败'
            };
        }
    }

    // 获取简单列表（不关联用户信息）
    async listSimple() {
        const { ctx, service } = this;

        try {
            const query = ctx.query;
            const result = await service.good.getGoodsSimple(query);

            ctx.body = {
                code: 0,
                data: result,
                msg: '获取成功'
            };
        } catch (error) {
            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取列表失败'
            };
        }
    }

    // 获取我的商品
    async myGoods() {
        const { ctx, service } = this;

        try {
            // 从token中获取用户ID
            const decode = await this.verifyToken();

            const query = ctx.query;
            const result = await service.good.getUserGoods(decode.user_id, query);

            ctx.body = {
                code: 0,
                data: result,
                msg: '获取成功'
            };
        } catch (error) {
            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取我的商品失败'
            };
        }
    }

    // 获取商品详情
    async detail() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;

            // 验证ID参数
            const rules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(rules, ctx.params);

            const good = await service.good.getGoodById(id);

            ctx.body = {
                code: 0,
                data: good,
                msg: '获取成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取商品详情失败'
            };
        }
    }

    // 更新商品信息
    async update() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;
            const updateData = ctx.request.body;

            // 验证路径参数
            const paramRules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(paramRules, ctx.params);

            // 验证body参数 - images允许字符串或数组
            const bodyRules = {
                title: { type: 'string', required: false, max: 100 },
                description: { type: 'string', required: false },
                category: { type: 'string', required: false, max: 50 },
                price: { type: 'number', required: false, min: 0 },
                images: { type: 'string', required: false }, // 主要验证字符串
                contact_info: { type: 'string', required: false }
            };
            ctx.validate(bodyRules);

            // 特殊处理images字段：如果是数组，转换为字符串
            if (updateData.images && Array.isArray(updateData.images)) {
                updateData.images = updateData.images.join(',');
            }

            // 从token中获取用户ID
            const decode = await this.verifyToken();

            // 检查商品是否存在且属于当前用户
            const good = await ctx.model.Good.findByPk(id);
            if (!good) {
                throw new Error('商品不存在');
            }

            if (good.user_id !== decode.user_id) {
                throw new Error('只能修改自己发布的商品');
            }

            const result = await service.good.updateGood(id, updateData);

            ctx.body = {
                code: 0,
                data: result,
                msg: '更新成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '更新商品信息失败'
            };
        }
    }

    // 更新商品状态
    async updateStatus() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;
            const { status } = ctx.request.body;

            // 验证路径参数
            const paramRules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(paramRules, ctx.params);

            // 验证body参数
            const bodyRules = {
                status: { type: 'number', required: true, min: 0, max: 2 }
            };
            ctx.validate(bodyRules);

            // 从token中获取用户ID
            const decode = await this.verifyToken();

            // 检查商品是否存在且属于当前用户
            const good = await ctx.model.Good.findByPk(id);
            if (!good) {
                throw new Error('商品不存在');
            }

            if (good.user_id !== decode.user_id) {
                throw new Error('只能修改自己发布的商品');
            }

            const result = await service.good.updateGoodStatus(id, status);

            ctx.body = {
                code: 0,
                data: result,
                msg: '状态更新成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '更新状态失败'
            };
        }
    }

    // 删除商品
    async delete() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;

            // 验证ID参数
            const rules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(rules, ctx.params);

            // 从token中获取用户ID
            const decode = await this.verifyToken();

            // 检查商品是否存在且属于当前用户
            const good = await ctx.model.Good.findByPk(id);
            if (!good) {
                throw new Error('商品不存在');
            }

            if (good.user_id !== decode.user_id) {
                throw new Error('只能删除自己发布的商品');
            }

            await service.good.deleteGood(id);

            ctx.body = {
                code: 0,
                data: null,
                msg: '删除成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '删除商品失败'
            };
        }
    }
}

module.exports = GoodController;